import React, { useCallback, useEffect, useRef, forwardRef, useImperativeHandle } from "react";
import { Button } from "antd";
import { useMemoizedFn, useSafeState } from "ahooks";


const defaultCount = 59;

interface IProps {
    sendEmailCaptcha: () => Promise<any>;
}

const CaptchaButton = (props: IProps, ref: any) => {
    const { sendEmailCaptcha } = props;
    const [count, setCount] = useSafeState(defaultCount);
    const [effecttive, setEffecttive] = useSafeState(false);
    const timerRef = useRef<ReturnType<typeof setInterval> | null>(null)
    const timerCallback = useMemoizedFn(() => {
        setCount(count - 1);
    })
    
    const clear = useCallback(() => {
        if (timerRef.current) {
            clearInterval(timerRef.current);
            setEffecttive(false)
            setCount(defaultCount)
        }
      }, []);

      useImperativeHandle(ref, () => {
        return {
            onSendCode
        }
      })

    // 发送验证码
    const onSendCode = async () => {
        let result = await sendEmailCaptcha();
        if(result.statusCode === '0') {
            // 邮箱验证码发送次数
            setEffecttive(true)
            timerRef.current = setInterval(timerCallback, 1000)
        }
    }

    useEffect(() => {
        if(count === 1) {
            clear();
        }
    }, [count])

    useEffect(() => {
        return () => {
            clear();
        };
    }, []);

    return (
        <Button type={effecttive ? 'default':'primary'} onClick={onSendCode} disabled={effecttive}>{ effecttive ? count: '发送验证码' }</Button>
    )
}

export default forwardRef(CaptchaButton);
